package com.eedi.org.utils;

import org.springframework.core.io.ClassPathResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Project eedi-org
 * @Description
 * @Author TomBombadil
 * @Date 2024/08/12 09:29
 **/
public class HttpResponseUtil {

    public static void writeFile2Response(HttpServletResponse response,String classPathFile) throws IOException {
        ClassPathResource resource = new ClassPathResource(classPathFile);
        InputStream in = resource.getInputStream();

        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", classPathFile));
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream out = response.getOutputStream();

        int len = 0;
        byte[] buffer = new byte[1024];
        while((len = in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }
}
